<template>
  <div class="ArresterTranscribe">
    <div class="filter">
      <el-form :model="filterForm" :rules="filterRules" ref="filterForm" label-width="120px">
        <el-form-item label="巡检类型:">
          <el-radio-group v-model="filterForm.inspectionType">
            <el-radio
              v-for="item in inspectionTypeList"
              :key="item.id"
              :label="item.id"
              :disabled="item.id !== filterForm.inspectionType"
            >{{item.name}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label v-if="specialInspectionTypeList">
          <el-radio-group v-model="filterForm.specialInspectionType">
            <el-radio
              v-for="item in specialInspectionTypeList"
              :key="item.id"
              :label="item.id"
              :disabled="item.id !== filterForm.specialInspectionType"
            >{{item.name}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="特巡模式:" v-if="specialInspectionModeList">
          <el-radio-group v-model="filterForm.specialInspectionMode">
            <el-radio
              v-for="item in specialInspectionModeList"
              :key="item.id"
              :label="item.id"
            >{{item.name}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="设备区域:">
          <div class="el_consist" :style="'height:' + (d_a_CheckMore ? 'auto' : '31px')">
            <el-checkbox
              class="allCheckBox"
              :label="0"
              name="type"
              :indeterminate="d_a_isIndeterminate"
              v-model="d_a_CheckAll"
              @change="handle_d_a_CheckAllChange"
            >全部</el-checkbox>
            <el-checkbox-group
              v-model="filterForm.deviceAreasCheckList"
              @change="handleCheckChange"
            >
              <el-checkbox
                v-for="item in deviceAreasList"
                :key="item.id"
                :label="item.id"
                name="type"
              >{{item.name}}</el-checkbox>
            </el-checkbox-group>
          </div>
          <el-checkbox
            v-if="deviceAreasList.length > nRowCount - 1"
            class="moreCheckBox"
            label="all"
            name="type"
            v-model="d_a_CheckMore"
            @change="handleMoreChange"
          >查看更多</el-checkbox>
        </el-form-item>
        <el-form-item label="设备类型:">
          <div class="el_consist" :style="'height:' + (d_t_CheckMore ? 'auto' : '31px')">
            <el-checkbox
              class="allCheckBox"
              :label="0"
              name="type"
              :indeterminate="d_t_isIndeterminate"
              v-model="d_t_CheckAll"
              @change="handle_d_t_CheckAllChange"
            >全部</el-checkbox>
            <el-checkbox-group v-model="filterForm.deviceTypeCheckList" @change="handleCheckChange">
              <el-checkbox
                v-for="item in deviceTypeList"
                :key="item.id"
                :label="item.id"
                name="type"
              >{{item.displayName}}</el-checkbox>
            </el-checkbox-group>
          </div>
          <el-checkbox
            v-if="deviceTypeList.length > nRowCount - 1"
            class="moreCheckBox"
            label="all"
            name="type"
            v-model="d_t_CheckMore"
            @change="handleMoreChange"
          >查看更多</el-checkbox>
        </el-form-item>
        <el-form-item label="识别类型:">
          <div class="el_consist" :style="'height:' + (r_t_CheckMore ? 'auto' : '31px')">
            <el-checkbox
              class="allCheckBox"
              :label="0"
              name="type"
              :indeterminate="r_t_isIndeterminate"
              v-model="r_t_CheckAll"
              @change="handle_r_t_CheckAllChange"
            >全部</el-checkbox>
            <el-checkbox-group
              v-model="filterForm.recognitionTypeCheckList"
              @change="handleCheckChange"
            >
              <el-checkbox
                v-for="item in recognitionTypeList"
                :key="item.id"
                :label="item.id"
                name="type"
              >{{item.name}}</el-checkbox>
            </el-checkbox-group>
          </div>
          <el-checkbox
            v-if="recognitionTypeList.length > nRowCount - 1"
            class="moreCheckBox"
            label="all"
            name="type"
            v-model="r_t_CheckMore"
            @change="handleMoreChange"
          >查看更多</el-checkbox>
        </el-form-item>
        <el-form-item label="表计类型:">
          <div class="el_consist" :style="'height:' + (m_t_CheckMore ? 'auto' : '31px')">
            <el-checkbox
              class="allCheckBox"
              :label="0"
              name="type"
              :indeterminate="m_t_isIndeterminate"
              v-model="m_t_CheckAll"
              @change="handle_m_t_CheckAllChange"
            >全部</el-checkbox>
            <el-checkbox-group
              v-model="filterForm.meterTypeCheckList"
              @change="handleCheckChange_meter"
            >
              <el-checkbox
                v-for="item in meterTypeList"
                :key="item.id"
                :label="item.id"
                name="type"
              >{{item.name}}</el-checkbox>
            </el-checkbox-group>
          </div>
          <el-checkbox
            v-if="meterTypeList.length > nRowCount - 1"
            class="moreCheckBox"
            label="all"
            name="type"
            v-model="m_t_CheckMore"
            @change="handleMoreChange"
          >查看更多</el-checkbox>
        </el-form-item>
        <el-form-item label="设备外观类型:">
          <div class="el_consist" :style="'height:' + (d_a_t_CheckMore ? 'auto' : '31px')">
            <el-checkbox
              class="allCheckBox"
              :label="0"
              name="type"
              :indeterminate="d_a_t_isIndeterminate"
              v-model="d_a_t_CheckAll"
              @change="handle_d_a_t_CheckAllChange"
            >全部</el-checkbox>
            <el-checkbox-group
              v-model="filterForm.deviceAppearanceTypeCheckList"
              @change="handleCheckChange_face"
            >
              <el-checkbox
                v-for="item in deviceAppearanceTypeList"
                :key="item.id"
                :label="item.id"
                name="type"
              >{{item.name}}</el-checkbox>
            </el-checkbox-group>
          </div>
          <el-checkbox
            v-if="deviceAppearanceTypeList.length > nRowCount - 1"
            class="moreCheckBox"
            label="all"
            name="type"
            v-model="d_a_t_CheckMore"
            @change="handleMoreChange"
          >查看更多</el-checkbox>
        </el-form-item>
        <div class="operation">
          <el-form-item>
            <el-input class="yd-input" v-model="queryStr" maxlength="15"></el-input>
          </el-form-item>
          <el-button class="but-query" type="text" size="medium" @click="handleQuery">
            <i class="query-icon"></i>查询
          </el-button>
          <el-button
            class="but-save"
            type="text"
            size="medium"
            :loading="saveLoading"
            @click="handleSave"
          >
            <i class="save-icon"></i>保存
          </el-button>
          <el-button class="but-remove" type="text" size="medium" @click="handleRemove">
            <i class="remove-icon"></i>删除
          </el-button>
          <el-button class="but-reset" type="text" size="medium" @click="handleReset">
            <i class="reset-icon"></i>重置
          </el-button>
        </div>
      </el-form>
    </div>
    <div class="content">
      <div class="content-left">
        <div class="left-head">设备树({{treeCheckNum}})</div>
        <div class="tree-list">
          <Tree-List
            ref="TreeList"
            :data="AllDeviceTreeList"
            :showCheckbox="true"
            :showIcon="true"
            :showState="true"
            @vtl_dataChange="vtl_dataChange"
            @vtl_nodeClick="vtl_nodeClick"
            @vtl_nodeLabelClick="vtl_nodeClick"
            @vtl_nodeCheckedChange="vtl_checkedChange"
          ></Tree-List>
        </div>
      </div>
      <div class="content-right">
        <div class="right-head">任务编制列表</div>
        <div class="content-list">
          <el-table
            ref="tasksTable"
            :data="tasksList"
            border
            size="mini"
            class="el-table-redefine"
            style="width: 100%"
            height="100%"
            :row-class-name="tableRowClassName"
            :row-style="tableRowStyle"
            @select="handleSelect"
            @selection-change="handleSelectionChange"
            @row-click="handleClick"
          >
            <el-table-column type="index" label="序号" align="center" width="50"></el-table-column>
            <el-table-column type="selection" align="center" width="50"></el-table-column>
            <el-table-column prop="name" label="任务名称"></el-table-column>
            <el-table-column prop="updateTime" label="编制时间"></el-table-column>
            <el-table-column align="center" label="操作">
              <template slot-scope="scope">
                <el-button type="text" size="mini" @click.stop="nowExecuted(scope)">立即执行</el-button>
                <el-button type="text" size="mini" @click.stop="timingExecuted(scope)">定时执行</el-button>
                <el-button type="text" size="mini" @click.stop="cycleExecuted(scope)">周期执行</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination-area">
          <el-pagination
            layout="total, sizes, prev, pager, next, jumper, slot"
            :page-sizes="[20, 50, 100, 300]"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :total="tansksTotal"
            :page-size="tasksQuery.size"
            :current-page="tasksQuery.page"
          >
            <el-button type="text" size="mini">前往</el-button>
          </el-pagination>
        </div>
        <Regularly-Perform ref="RegularlyPerform" :data="regularlyEditRowData"></Regularly-Perform>
        <Cycle-Perform ref="CyclePerform" :data="cycleEditRowData"></Cycle-Perform>
      </div>
    </div>
  </div>
</template>
<script>
import {
  inspectTypesList,
  inspectTypesTree,
  devicesAreas,
  devicesTypesList,
  reconTypesList,
  meterTypesList,
  faceTypesList,
  pointsTree,
  tasksList,
  tasksAdd,
  tasksUpdate,
  tasksDelete,
  tasksPointsList,
  tasksEditStatus,
  tasksExecutStatus,
  inspectTypeChoosesDefaultChecks,
  robotParams,
  robotsCurrentTask,
  postOperationLogs
} from "@/api/apiManagement";

import RegularlyPerform from "./components/RegularlyPerform";
import CyclePerform from "./components/CyclePerform";
import TreeList from "@/components/TreeList";

export default {
  components: { RegularlyPerform, CyclePerform, TreeList },

  data() {
    return {
      robot_id: null,
      //
      robotInfo: {
        robotControlModel: null,
        robotOneClickReturnStatus: 0
      },
      //
      queryStr: "",
      //
      AllDeviceTreeList: [],
      treeCheckNum: 0,

      inspectTypesTree: [],
      // inspectionTypeList: [],
      // specialInspectionTypeList: [],
      // specialInspectionModeList: [],
      deviceAreasList: [],
      deviceTypeList: [],
      recognitionTypeList: [],
      meterTypeList: [],
      deviceAppearanceTypeList: [],
      //
      nRowCount: 0,
      //
      d_a_isIndeterminate: false,
      d_a_CheckAll: false,
      d_a_CheckMore: false,
      d_t_isIndeterminate: false,
      d_t_CheckAll: false,
      d_t_CheckMore: false,
      r_t_isIndeterminate: false,
      r_t_CheckAll: false,
      r_t_CheckMore: false,
      m_t_isIndeterminate: false,
      m_t_CheckAll: false,
      m_t_CheckMore: false,
      d_a_t_isIndeterminate: false,
      d_a_t_CheckAll: false,
      d_a_t_CheckMore: false,
      //
      filterForm: {
        inspectionType: 3,
        specialInspectionType: 7,
        specialInspectionMode: null,
        deviceAreasCheckList: [],
        deviceTypeCheckList: [],
        recognitionTypeCheckList: [],
        meterTypeCheckList: [],
        deviceAppearanceTypeCheckList: []
      },
      filterRules: {},
      //
      saveLoading: false,
      //
      tasksForm: {
        description: "",
        inspectTypeId: 7,
        isCustom: 0,
        name: "",
        points: "",
        robotId: 1
      },
      //
      tasksList: [],
      tableSelection: null,
      regularlyEditRowData: {},
      cycleEditRowData: {},
      tansksTotal: 0,
      tasksQuery: {
        robotId: 1,
        inspectTypeId: 7,
        // custom: 0,
        page: 1,
        size: 20
      },
      rosObj: {
        ip: "",
        port: ""
      },
      urgencyTaskTime: null,
      urgencyTaskData: null,
      bUrgencyTask: false,
      urgencyTaskLoading: null
    };
  },
  watch: {
    "filterForm.deviceAreasCheckList": function(val, oldVal) {
      let checkedCount = val.length;
      this.d_a_CheckAll = checkedCount === this.deviceAreasList.length;
      this.d_a_isIndeterminate =
        checkedCount > 0 && checkedCount < this.deviceAreasList.length;
    },
    "filterForm.deviceTypeCheckList": function(val, oldVal) {
      let checkedCount = val.length;
      this.d_t_CheckAll = checkedCount === this.deviceTypeList.length;
      this.d_t_isIndeterminate =
        checkedCount > 0 && checkedCount < this.deviceTypeList.length;
    },
    "filterForm.recognitionTypeCheckList": function(val, oldVal) {
      let checkedCount = val.length;
      this.r_t_CheckAll = checkedCount === this.recognitionTypeList.length;
      this.r_t_isIndeterminate =
        checkedCount > 0 && checkedCount < this.recognitionTypeList.length;
    },
    "filterForm.meterTypeCheckList": function(val, oldVal) {
      let checkedCount = val.length;
      this.m_t_CheckAll = checkedCount === this.meterTypeList.length;
      this.m_t_isIndeterminate =
        checkedCount > 0 && checkedCount < this.meterTypeList.length;
    },
    "filterForm.deviceAppearanceTypeCheckList": function(val, oldVal) {
      let checkedCount = val.length;
      this.d_a_t_CheckAll =
        checkedCount === this.deviceAppearanceTypeList.length;
      this.d_a_t_isIndeterminate =
        checkedCount > 0 && checkedCount < this.deviceAppearanceTypeList.length;
    }
  },
  computed: {
    inspectionTypeList: function() {
      if (this.inspectTypesTree) {
        return this.inspectTypesTree;
      }
    },
    specialInspectionTypeList: function() {
      if (this.inspectionTypeList) {
        for (var i = 0, len = this.inspectionTypeList.length; i < len; i++) {
          if (
            this.inspectionTypeList[i].id === this.filterForm.inspectionType
          ) {
            return this.inspectionTypeList[i].children;
          }
        }
      }
    },
    specialInspectionModeList: function() {
      if (this.specialInspectionTypeList) {
        for (
          var i = 0, len = this.specialInspectionTypeList.length;
          i < len;
          i++
        ) {
          if (
            this.specialInspectionTypeList[i].id ===
            this.filterForm.specialInspectionType
          ) {
            return this.specialInspectionTypeList[i].children;
          }
        }
      }
    }
  },
  created() {
    this.robot_id = localStorage.getItem("ydRobot_id");
    this.tasksQuery.robotId = this.robot_id;
    this.tasksForm.robotId = this.robot_id;
    this.getRobotParams({
      page: 1,
      size: 0,
      robotId: this.robot_id,
      type: 3
    });
    //
    this.getRobotsCurrentTask();
    // 巡检类型树
    this.getInspectTypesTree();
    // 巡检类型
    this.getInspectTypesList();
    // 设备区域
    this.getDevicesAreas();
    // 设备类型
    this.getDevicesTypesList();
    // 识别类型
    this.getReconTypesList();
    // 表计类型
    this.getMeterTypesList();
    // 设备外观类型
    this.getFaceTypeList();
    // 任务列表
    this.getTasksList();
    // 巡检类型默认配置
    this.getInspectTypeChoosesDefaultChecks();
    // // 点位树
    // this.getPointsTree();
  },
  mounted() {
    this.initRos();
    this.nRowCount =
      document.getElementsByClassName("el_consist")[0].clientWidth / 251;
    // 监听窗口大小
    window.onresize = () => {
      this.nRowCount =
        document.getElementsByClassName("el_consist")[0].clientWidth / 251;
    };
  },
  destroyed() {
    this.taskRealStatusWebUnCallBack();
    this.controlModelStatusUnCallBack();
    this.oneButtonTaskStatusUnCallBack();
  },
  methods: {
    /**
     * 该方法用于将有父子关系的数组转换成树形结构的数组
     * 接收一个具有父子关系的数组作为参数
     * 返回一个树形结构的数组
     */
    translateArrayToTree(data) {
      let tempData = data;
      //没有父节点的数据
      let parent = data.filter(item => {
        if (item.parentId == "undefined" || item.parentId == null) {
          return true;
        } else {
          if (tempData.some(it => it.id === item.parentId)) {
            return false;
          } else {
            return true;
          }
        }
      });
      //有父节点的数据
      let children = data.filter(item => {
        if (item.parentId !== "undefined" && item.parentId != null) {
          if (tempData.some(it => it.id === item.parentId)) {
            return true;
          } else {
            return false;
          }
        } else {
          return false;
        }
      });
      //定义转换方法的具体实现
      let translator = (parent, children) => {
        //遍历父节点数据
        parent.forEach(parentItem => {
          //遍历子节点数据
          children.forEach((childrenItem, index) => {
            //此时找到父节点对应的一个子节点
            if (parentItem.id === childrenItem.parentId) {
              //对子节点数据进行深复制，这里只支持部分类型的数据深复制，对深复制不了解的童靴可以先去了解下深复制
              let temp = JSON.parse(JSON.stringify(children));
              //让当前子节点从temp中移除，temp作为新的子节点数据，这里是为了让递归时，子节点的遍历次数更少，如果父子关系的层级越多，越有利
              temp.splice(index, 1);
              //让当前子节点作为唯一的父节点，去递归查找其对应的子节点
              translator([childrenItem], temp);
              //把找到子节点放入父节点的children属性中
              typeof parentItem.children !== "undefined" &&
              parentItem.children !== null
                ? parentItem.children.push(childrenItem)
                : (parentItem.children = [childrenItem]);
            }
          });
        });
      };
      //调用转换方法
      translator(parent, children);
      //返回最终的结果
      return parent;
    },
    // 巡检类型树
    getInspectTypesTree() {
      inspectTypesTree()
        .then(response => {
          if (response) {
            this.inspectTypesTree = response;
          }
        })
        .catch(() => {});
    },
    // 巡检类型
    getInspectTypesList() {
      inspectTypesList()
        .then(response => {
          if (response.list) {
            // this.inspectionTypeList = response.list.filter(item => {
            //   return item.level === 1 && item.parentId === 0;
            // });
          }
        })
        .catch(() => {});
    },
    // 设备区域
    getDevicesAreas() {
      devicesAreas()
        .then(response => {
          if (response) {
            this.deviceAreasList = response;
          }
        })
        .catch(() => {});
    },
    // 设备类型
    getDevicesTypesList() {
      devicesTypesList()
        .then(response => {
          if (response.list) {
            this.deviceTypeList = response.list.filter(item => {
              return parseInt(item.name) >= 2000;
            });
          }
        })
        .catch(() => {});
    },
    // 识别类型
    getReconTypesList() {
      reconTypesList()
        .then(response => {
          if (response.list) {
            this.recognitionTypeList = response.list;
          }
        })
        .catch(() => {});
    },
    // 表计类型
    getMeterTypesList() {
      meterTypesList()
        .then(response => {
          if (response.list) {
            this.meterTypeList = response.list;
          }
        })
        .catch(() => {});
    },
    // 设备外观类型
    getFaceTypeList() {
      faceTypesList()
        .then(response => {
          if (response.list) {
            this.deviceAppearanceTypeList = response.list;
          }
        })
        .catch(() => {});
    },
    // 巡检类型默认配置
    getInspectTypeChoosesDefaultChecks() {
      inspectTypeChoosesDefaultChecks({
        inspectId: this.filterForm.specialInspectionType
      }).then(response => {
        if (response) {
          for (var i = 0, len = response.length; i < len; i++) {
            if (
              response[i].inspectTypeId ===
              this.filterForm.specialInspectionType
            ) {
              if (response[i].chooseType === 0) {
                if (
                  !this.filterForm.deviceAreasCheckList.some(
                    item => item === response[i].chooseId
                  )
                ) {
                  this.filterForm.deviceAreasCheckList.push(
                    response[i].chooseId
                  );
                }
              }
              if (response[i].chooseType === 1) {
                if (
                  !this.filterForm.deviceTypeCheckList.some(
                    item => item === response[i].chooseId
                  )
                ) {
                  this.filterForm.deviceTypeCheckList.push(
                    response[i].chooseId
                  );
                }
              }
              if (response[i].chooseType === 2) {
                if (
                  !this.filterForm.recognitionTypeCheckList.some(
                    item => item === response[i].chooseId
                  )
                ) {
                  this.filterForm.recognitionTypeCheckList.push(
                    response[i].chooseId
                  );
                }
              }
              if (response[i].chooseType === 3) {
                if (
                  !this.filterForm.meterTypeCheckList.some(
                    item => item === response[i].chooseId
                  )
                ) {
                  this.filterForm.meterTypeCheckList.push(response[i].chooseId);
                }
              }
              if (response[i].chooseType === 4) {
                if (
                  !this.filterForm.deviceAppearanceTypeCheckList.some(
                    item => item === response[i].chooseId
                  )
                ) {
                  this.filterForm.deviceAppearanceTypeCheckList.push(
                    response[i].chooseId
                  );
                }
              }
            }
          }
        }
        this.getPointsTree();
      });
    },
    // 点位树
    getPointsTree() {
      pointsTree()
        .then(response => {
          if (response) {
            this.AllDeviceTreeList = response;
            //
            this.pointsFilter();
          }
        })
        .catch(() => {});
    },
    // 任务列表
    getTasksList() {
      tasksList(this.tasksQuery)
        .then(response => {
          this.tansksTotal = response.total;
          if (response.list) {
            this.tasksList = response.list;
          }
        })
        .catch(() => {});
    },
    //
    conditionFilter(data) {
      if (data && data.length > 0) {
        for (let index = 0; index < data.length; index++) {
          if (data[index].modelLevel) {
            if (data[index].modelLevel == 1010) {
              if (
                !this.filterForm.deviceAreasCheckList.some(
                  t => t === data[index].id
                )
              ) {
                this.filterForm.deviceAreasCheckList.push(data[index].id);
              }
            }
            if (data[index].modelLevel == 1200) {
              if (
                !this.filterForm.deviceTypeCheckList.some(
                  t => t === data[index].deviceTypeId
                )
              ) {
                this.filterForm.deviceTypeCheckList.push(
                  data[index].deviceTypeId
                );
              }
            }
          } else {
            if (
              !this.filterForm.recognitionTypeCheckList.some(
                t => t === data[index].reconTypeId
              )
            ) {
              this.filterForm.recognitionTypeCheckList.push(
                data[index].reconTypeId
              );
            }
            if (
              data[index].meterTypeId != 0 &&
              !this.filterForm.meterTypeCheckList.some(
                t => t === data[index].meterTypeId
              )
            ) {
              this.filterForm.meterTypeCheckList.push(data[index].meterTypeId);
            }
            if (
              data[index].faceTypeId != 0 &&
              !this.filterForm.deviceAppearanceTypeCheckList.some(
                t => t === data[index].faceTypeId
              )
            ) {
              this.filterForm.deviceAppearanceTypeCheckList.push(
                data[index].faceTypeId
              );
            }
          }
        }
      }
    },
    pointsFilter() {
      this.$refs.TreeList.vtl_nodesFilter({
        deviceAreasList: this.filterForm.deviceAreasCheckList,
        deviceTypeList: this.filterForm.deviceTypeCheckList,
        recognitionTypeList: this.filterForm.recognitionTypeCheckList,
        meterTypeList: this.filterForm.meterTypeCheckList,
        deviceAppearanceTypeList: this.filterForm.deviceAppearanceTypeCheckList,
        useList: [],
        pointType: []
      });
      let points = [];
      points = this.$refs.TreeList.vtl_getAllLeafNodesId();
      if (
        this.filterForm.deviceAreasCheckList &&
        this.filterForm.deviceAreasCheckList.length <= 0 &&
        this.filterForm.deviceTypeCheckList &&
        this.filterForm.deviceTypeCheckList.length <= 0 &&
        this.filterForm.recognitionTypeCheckList &&
        this.filterForm.recognitionTypeCheckList.length <= 0 &&
        this.filterForm.meterTypeCheckList &&
        this.filterForm.meterTypeCheckList.length <= 0 &&
        this.filterForm.deviceAppearanceTypeCheckList &&
        this.filterForm.deviceAppearanceTypeCheckList.length <= 0
      ) {
        points = [];
      }
      this.$refs.TreeList.vtl_setCheckedNodesId(points);
    },
    //
    vtl_nodeClick(list, table, index, data) {
      this.$refs.TreeList.vtl_setCheckedNodesSingleId({ id: data.id });
    },
    vtl_checkedChange(list, table, index, data) {
      this.treeCheckNum = this.$refs.TreeList.vtl_getCheckedNodes().filter(
        item => item.leaf == true
      ).length;
    },
    //
    vtl_dataChange(treeList, treeTable, treeIndexes) {
      this.pointsFilter();
    },
    //
    newTasksAdd() {
      let tempData = this.$refs.TreeList.vtl_getCheckedNodesId();
      let pointData = tempData
        .filter(item => {
          if (item.toString().indexOf("point_") != -1) {
            return true;
          }
        })
        .map(item => {
          return item.substring(6, item.length);
        });
      if (pointData.length > 0) {
        this.saveLoading = !this.saveLoading;
        this.tasksForm.points = pointData.join(",");
        if (this.tableSelection) {
          this.tasksForm.name = this.tableSelection.name;
          this.tasksForm.description = this.tableSelection.description;
          this.tasksForm.robotId = this.tableSelection.robotId;
          tasksEditStatus({}, this.tableSelection.id)
            .then(res => {
              if (res.editStatus) {
                tasksUpdate(this.tasksForm, this.tableSelection.id)
                  .then(response => {
                    this.setOperationLogs(
                      "修改-" + this.tasksForm.name + "-任务"
                    );

                    this.getTasksList();
                    this.saveLoading = !this.saveLoading;
                    this.handleReset();
                    this.$alert("任务编辑成功", "提示", {
                      confirmButtonText: "确定",
                      callback: action => {
                        //
                      }
                    });
                  })
                  .catch(() => {
                    this.saveLoading = !this.saveLoading;
                  });
              } else {
                this.saveLoading = !this.saveLoading;
                this.$message({
                  message: "当前任务正在执行，无法编辑!"
                });
              }
            })
            .catch(() => {
              this.saveLoading = !this.saveLoading;
            });
        } else {
          if (this.filterForm.inspectionType === 3) {
            if (this.filterForm.specialInspectionType === 7) {
              this.tasksForm.inspectTypeId = this.filterForm.specialInspectionType;
              this.tasksForm.name = "避雷器表计抄录" + "专项巡视";
            }
          }
          tasksAdd(this.tasksForm)
            .then(response => {
              this.setOperationLogs("新增-" + this.tasksForm.name + "-任务");

              this.getTasksList();
              this.saveLoading = !this.saveLoading;
              this.handleReset();
              this.$alert("任务添加成功", "提示", {
                confirmButtonText: "确定",
                callback: action => {
                  //
                }
              });
            })
            .catch(() => {
              this.saveLoading = !this.saveLoading;
            });
        }
      } else {
        this.$message({
          message: "请添加点位!",
          type: "success"
        });
      }
    },
    //
    handle_d_a_CheckAllChange(val) {
      this.filterForm.deviceAreasCheckList = val
        ? this.deviceAreasList.map(item => {
            return item.id;
          })
        : [];

      this.pointsFilter();
    },
    //
    handle_d_t_CheckAllChange(val) {
      this.filterForm.deviceTypeCheckList = val
        ? this.deviceTypeList.map(item => {
            return item.id;
          })
        : [];

      this.pointsFilter();
    },
    //
    handle_r_t_CheckAllChange(val) {
      this.filterForm.recognitionTypeCheckList = val
        ? this.recognitionTypeList.map(item => {
            return item.id;
          })
        : [];

      this.pointsFilter();
    },
    //
    handle_m_t_CheckAllChange(val) {
      this.filterForm.meterTypeCheckList = val
        ? this.meterTypeList.map(item => {
            return item.id;
          })
        : [];

      this.pointsFilter();
    },
    //
    handle_d_a_t_CheckAllChange(val) {
      this.filterForm.deviceAppearanceTypeCheckList = val
        ? this.deviceAppearanceTypeList.map(item => {
            return item.id;
          })
        : [];

      this.pointsFilter();
    },
    //
    handleCheckChange(val) {
      this.pointsFilter();
    },
    handleCheckChange_meter(val) {
      if (this.filterForm.meterTypeCheckList.length > 0) {
        if (!this.filterForm.recognitionTypeCheckList.some(t => t === 1)) {
          this.filterForm.recognitionTypeCheckList.push(1);
        }
      } else {
        let index = this.filterForm.recognitionTypeCheckList.indexOf(1);
        if (index != -1) {
          this.filterForm.recognitionTypeCheckList.splice(index, 1);
        }
      }
      this.pointsFilter();
    },
    handleCheckChange_face(val) {
      if (this.filterForm.deviceAppearanceTypeCheckList.length > 0) {
        if (!this.filterForm.recognitionTypeCheckList.some(t => t === 3)) {
          this.filterForm.recognitionTypeCheckList.push(3);
        }
      } else {
        let index = this.filterForm.recognitionTypeCheckList.indexOf(3);
        if (index != -1) {
          this.filterForm.recognitionTypeCheckList.splice(index, 1);
        }
      }
      this.pointsFilter();
    },
    //
    handleMoreChange(val) {
      //
    },
    //
    handleQuery() {
      this.$refs.TreeList.vtl_nodesSearch({ str: this.queryStr });
    },
    handleSave() {
      this.newTasksAdd();
    },
    handleRemove() {
      if (this.tableSelection) {
        this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            tasksEditStatus({}, this.tableSelection.id)
              .then(res => {
                if (res.editStatus) {
                  tasksDelete({}, this.tableSelection.id)
                    .then(response => {
                      this.setOperationLogs(
                        "删除-" + this.tableSelection.name + "-任务"
                      );

                      this.getTasksList();
                      this.$message({
                        message: "删除成功!",
                        type: "success"
                      });
                    })
                    .catch(() => {});
                } else {
                  this.$message({
                    message: "当前任务正在执行，无法删除!"
                  });
                }
              })
              .catch(() => {
                this.saveLoading = !this.saveLoading;
              });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除"
            });
          });
      } else {
        this.$message({
          message: "请选择任务!"
        });
      }
    },
    handleReset() {
      this.queryStr = "";
      this.filterForm.deviceAreasCheckList = [];
      this.filterForm.deviceTypeCheckList = [];
      this.filterForm.recognitionTypeCheckList = [];
      this.filterForm.meterTypeCheckList = [];
      this.filterForm.deviceAppearanceTypeCheckList = [];
      this.$refs.tasksTable.clearSelection();
      // 巡检类型默认配置
      this.getInspectTypeChoosesDefaultChecks();
    },
    //
    tableRowClassName({ row, rowIndex }) {
      return this.tableSelection && this.tableSelection.id === row.id
        ? "edit-row"
        : "";
    },
    tableRowStyle({ row, rowIndex }) {
      return "";
    },
    handleSelect(selection, row) {
      this.filterForm.deviceAreasCheckList = [];
      this.filterForm.deviceTypeCheckList = [];
      this.filterForm.recognitionTypeCheckList = [];
      this.filterForm.meterTypeCheckList = [];
      this.filterForm.deviceAppearanceTypeCheckList = [];
      this.pointsFilter();
      //
      if (selection.length >= 1) {
        tasksPointsList({}, row.id)
          .then(response => {
            let tempPoints = response.map(item => {
              return "point_" + item.pointId;
            });
            this.$refs.TreeList.vtl_setCheckedNodesId(tempPoints);
            let checkedNodes = this.$refs.TreeList.vtl_getHalfCheckedNodes();
            //
            this.conditionFilter(checkedNodes);
          })
          .catch(() => {});
      }
    },
    handleSelectionChange(val) {
      if (val.length > 1) {
        this.$refs.tasksTable.clearSelection();
        this.$refs.tasksTable.toggleRowSelection(val.pop());
        this.tableSelection = val.pop();
      } else {
        if (val.length === 1) {
          this.tableSelection = val[0];
        } else {
          this.tableSelection = null;
        }
      }
    },
    handleClick(row, column, event) {
      this.filterForm.deviceAreasCheckList = [];
      this.filterForm.deviceTypeCheckList = [];
      this.filterForm.recognitionTypeCheckList = [];
      this.filterForm.meterTypeCheckList = [];
      this.filterForm.deviceAppearanceTypeCheckList = [];
      this.pointsFilter();
      //
      if (!this.tableSelection || row.id != this.tableSelection.id) {
        this.$refs.tasksTable.clearSelection();
        this.$refs.tasksTable.toggleRowSelection(row);
        tasksPointsList({}, row.id)
          .then(response => {
            let tempPoints = response.map(item => {
              return "point_" + item.pointId;
            });
            this.$refs.TreeList.vtl_setCheckedNodesId(tempPoints);
            let checkedNodes = this.$refs.TreeList.vtl_getHalfCheckedNodes();
            //
            this.conditionFilter(checkedNodes);
          })
          .catch(() => {});
      } else {
        this.$refs.tasksTable.clearSelection();
      }
    },
    //
    urgencyTask(data) {
      this.$confirm("立即执行当前任务, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          if (data) {
            this.setOperationLogs("立即执行-" + data.row.name + "-任务");
            //
            var status = this.urgencyTaskPub({
              robot_id: data.row.robotId,
              task_id: data.row.id,
              task_level: data.row.inspectType.level,
              // task_type: data.row.inspectTypeId
              task_type: 4
            });
            if (status != 0) {
              this.$message({
                type: "warning",
                message: "机器人连接失败!"
              });
              return;
            }
            //
            this.urgencyTaskData = data.row;
            this.bUrgencyTask = true;
            this.urgencyTaskLoading = this.$loading({
              lock: true,
              text: "任务规划中，请稍后...",
              spinner: "el-icon-loading",
              customClass: "urgency-task-loading",
              background: "rgba(0, 0, 0, 0.7)"
            });
            this.urgencyTaskTime = setTimeout(() => {
              this.urgencyTaskData = null;
              this.bUrgencyTask = false;
              this.urgencyTaskLoading.close();
              this.$confirm("任务执行超时！", "提示", {
                showCancelButton: false,
                confirmButtonText: "确定",
                type: "warning"
              });
            }, 60000);
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消执行"
          });
        });
    },
    nowExecuted(data) {
      if (this.robotInfo.robotOneClickReturnStatus == 1) {
        this.$message({
          type: "warning",
          message: "一键返航中，无法下发任务!"
        });
      } else {
        if (this.robotInfo.robotControlModel == 0) {
          tasksExecutStatus({}, data.row.id)
            .then(res => {
              if (res.status) {
                this.urgencyTask(data);
              } else {
                this.$message({
                  type: "warning",
                  message: "当前已有高等级任务正在执行，无法下发当前任务!"
                });
              }
            })
            .catch(() => {});
        } else {
          this.$message({
            type: "warning",
            message: "当前机器人不是任务模式，无法下发任务!"
          });
        }
      }
    },
    //
    timingExecuted(data) {
      this.regularlyEditRowData = data.row;
      this.$refs.RegularlyPerform.isShowDia(true);
    },
    //
    cycleExecuted(data) {
      this.cycleEditRowData = data.row;
      this.$refs.CyclePerform.isShowDia(true);
    },
    //
    handleSizeChange(val) {
      this.tasksQuery.size = val;
      this.getTasksList();
    },
    //
    handleCurrentChange(val) {
      this.tasksQuery.page = val;
      this.getTasksList();
    },
    getRobotParams(data) {
      robotParams(data)
        .then(response => {
          if (response.list && response.list.length > 0) {
            for (var i = 0, len = response.list.length; i < len; i++) {
              if (response.list[i].name === "ros_websocket_ip") {
                this.rosObj.ip = response.list[i].value;
              }
              if (response.list[i].name === "ros_websocket_port") {
                this.rosObj.port = response.list[i].value;
              }
            }
          }
        })
        .catch(() => {});
    },
    getRobotsCurrentTask() {
      robotsCurrentTask({}, this.robot_id)
        .then(res => {
          if (res) {
            if (this.taskInfo.type == 2) {
              this.robotInfo.robotOneClickReturnStatus = 1;
            } else {
              this.robotInfo.robotOneClickReturnStatus = 0;
            }
          }
        })
        .catch(() => {});
    },
    initRos() {
      this.taskRealStatusWebCallBack(message => {
        console.log("robotTaskRealStatusWeb", message);
        // robot_id task_history_id task_status
        // 任务状态 0:已执行 1:终止 2:暂停 3:正在执行 4:未执行 5:超期 6:预执行 7:超时
        if (this.bUrgencyTask) {
          if (this.robot_id == message.robot_id) {
            if (
              this.urgencyTaskData &&
              message.task_id == this.urgencyTaskData.id
            ) {
              if (message.task_status == 3) {
                this.urgencyTaskData = null;
                this.bUrgencyTask = false;
                this.urgencyTaskLoading.close();
                clearTimeout(this.urgencyTaskTime);
                this.$message({
                  message: "任务开始!",
                  type: "success",
                  duration: 3000
                });
                setTimeout(() => {
                  this.$router.push({
                    path: "/monitors/inspection-monitoring"
                  });
                }, 3000);
              }
              // if (message.task_status == 4) {
              //   this.urgencyTaskData = null;
              //   this.bUrgencyTask = false;
              //   this.urgencyTaskLoading.close();
              //   clearTimeout(this.urgencyTaskTime);
              //   this.$message({
              //     message: "任务已插入队列，等待执行!",
              //     type: "success",
              //     duration: 3000
              //   });
              // }
              if (message.task_status == 7) {
                this.urgencyTaskData = null;
                this.bUrgencyTask = false;
                this.urgencyTaskLoading.close();
                clearTimeout(this.urgencyTaskTime);
                this.$confirm("任务执行超时！", "提示", {
                  showCancelButton: false,
                  confirmButtonText: "确定",
                  type: "warning"
                });
              }
            }
          }
        }
      });
      // console.log("robotControlMode", message);
      this.controlModelStatusCallBack(message => {
        if (message.robot_id == this.robot_id) {
          this.robotInfo.robotControlModel = message.mode;
        }
      });
      this.oneButtonTaskStatusCallBack(message => {
        console.log("robotOneButtonTaskStatus", message);
        if (this.robot_id == message.robotId) {
          this.robotInfo.robotOneClickReturnStatus = message.status;
        }
      });
    },
    // 添加日志管理
    setOperationLogs(content) {
      var parm = {
        content: content,
        deviceId: localStorage.getItem("ydRobot_device_id"),
        type: 0
      };
      postOperationLogs(parm)
        .then(response => {})
        .catch(() => {});
    }
  }
};
</script>

<style>
.ArresterTranscribe .filter .el-form-item {
  margin-top: 0;
  margin-bottom: 3px;
}
.ArresterTranscribe .filter .el-form-item__label {
  font-size: 13px;
  line-height: 26px;
}
.ArresterTranscribe .filter .el-form-item__content {
  font-size: 13px;
  line-height: 26px;
}
.ArresterTranscribe .filter .el-radio__label {
  font-size: 13px;
}
.ArresterTranscribe .filter .el-checkbox {
  font-size: 13px;
}
.ArresterTranscribe .filter .el-checkbox__label {
  font-size: 13px;
  padding-left: 6px;
}
.ArresterTranscribe .filter .el-radio {
  width: 210px;
  margin-left: 10px;
}
.ArresterTranscribe .filter .el-radio + .el-radio {
  margin-left: 10px;
}
.ArresterTranscribe .filter .el-checkbox {
  width: 210px;
  margin-left: 10px;
}
.ArresterTranscribe .filter .el-checkbox + .el-checkbox {
  margin-left: 10px;
}
.ArresterTranscribe .content-left .custom-tree-node span {
  font-size: 13px;
}
/*  */

.ArresterTranscribe {
  width: 100%;
  height: 100%;
  display: flex;
  flex-flow: column;
}
.ArresterTranscribe .filter {
  position: relative;
  width: 100%;
  /* height: 230px; */
  background-color: #eeeeee;
}
.ArresterTranscribe .el_consist {
  width: calc(100% - 220px);
  float: left;
  overflow: hidden;
}
.ArresterTranscribe .allCheckBox {
  float: left;
}
.ArresterTranscribe .moreCheckBox {
  float: right;
}
.ArresterTranscribe .operation {
  width: 100%;
  height: 30px;
  background: linear-gradient(
    rgb(227, 242, 238),
    rgb(202, 231, 238)
  ); /* 标准的语法 */
  border-top: 1px solid rgb(202, 231, 238);
}
.ArresterTranscribe .operation .el-form-item {
  margin-top: 0;
  margin-bottom: 0;
  float: left;
}
.ArresterTranscribe .operation .el-form-item__content {
  width: 200px;
  margin-left: 5px !important;
}
.ArresterTranscribe .yd-input {
  width: 200px;
  height: 30px;
  /* float: left; */
}
.ArresterTranscribe .yd-input .el-input__inner {
  height: 29px;
  line-height: 27px;
  padding: 0 6px;
  border: 1px solid rgb(202, 231, 238);
}
.ArresterTranscribe .but-query,
.ArresterTranscribe .but-save,
.ArresterTranscribe .but-remove,
.ArresterTranscribe .but-reset {
  height: 30px;
  margin-left: 20px;
  margin-right: 10px;
  padding: 0;
  font-size: 13px;
  color: #000;
  float: left;
}
.ArresterTranscribe .query-icon {
  width: 14px;
  height: 14px;
  margin-right: 3px;
  background-image: url(../../../static/resources/images/query.png);
  background-size: 100% 100%;
  float: left;
}
.ArresterTranscribe .save-icon {
  width: 14px;
  height: 14px;
  margin-right: 3px;
  background-image: url(../../../static/resources/images/save.png);
  background-size: 100% 100%;
  float: left;
}
.ArresterTranscribe .remove-icon {
  width: 14px;
  height: 14px;
  margin-right: 3px;
  background-image: url(../../../static/resources/images/remove.png);
  background-size: 100% 100%;
  float: left;
}
.ArresterTranscribe .reset-icon {
  width: 14px;
  height: 14px;
  margin-right: 3px;
  background-image: url(../../../static/resources/images/reset_a.png);
  background-size: 100% 100%;
  float: left;
}

.ArresterTranscribe .content {
  width: 100%;
  min-height: 360px;
  flex-grow: 1;
}
.ArresterTranscribe .content-left {
  position: relative;
  width: 300px;
  height: 100%;
  /* background-color: #eeeeee; */
  background-color: #fff;
  border-right: 1px solid rgb(202, 231, 238);
  float: left;
}
.ArresterTranscribe .content-right {
  position: relative;
  /* width: 100%; */
  width: calc(100% - 300px);
  height: 100%;
  /* margin-left: 300px; */
  /* padding: 0 0 0 10px; */
  border-left: 1px solid rgb(202, 231, 238);
  float: left;
}
.ArresterTranscribe .left-head {
  width: 100%;
  height: 27px;
  padding: 0 5px;
  line-height: 27px;
  font-size: 13px;
  background: linear-gradient(
    rgb(227, 242, 238),
    rgb(202, 231, 238)
  ); /* 标准的语法 */
}
.ArresterTranscribe .tree-list {
  position: absolute;
  width: 100%;
  height: calc(100% - 27px);
  overflow: auto;
}
.ArresterTranscribe .right-head {
  width: 100%;
  height: 27px;
  padding: 0 5px;
  line-height: 27px;
  font-size: 13px;
  background: linear-gradient(
    rgb(227, 242, 238),
    rgb(202, 231, 238)
  ); /* 标准的语法 */
}

.ArresterTranscribe .content-list {
  position: absolute;
  width: 100%;
  height: calc(100% - 59px);
  /* overflow: auto; */
}

.ArresterTranscribe .pagination-area {
  position: absolute;
  width: 100%;
  height: 32px;
  bottom: 0px;
  background-color: #eeeeee;
  /* position: fixed;
  right: 0px;
  bottom: 30px;
  background-color: #eeeeee;
  width: calc(100% - 301px);
  z-index: 1; */
}

.ArresterTranscribe .el-table-redefine {
  width: 100%;
  height: 100%;
  /* display: flex;
  flex-flow: column; */
}

.ArresterTranscribe .el-table-redefine .el-table__body-wrapper {
  /* overflow: hidden;
  overflow-y: auto;
  flex-grow: 1; */
}

.ArresterTranscribe .el-table-redefine thead .el-table-column--selection .cell {
  display: none;
}

.ArresterTranscribe .el-table-redefine .edit-row {
  background: rgb(230, 250, 230) !important;
}

.ArresterTranscribe .folder {
  width: 13px;
  height: 13px;
  margin-top: 3px;
  /* background-color: rgb(10, 158, 80); */
  background-image: url(../../../static/resources/images/folder.png);
  background-size: 100% 100%;
  float: left;
}
.ArresterTranscribe .file {
  width: 13px;
  height: 13px;
  margin-top: 3px;
  /* background-color: rgb(255, 0, 0); */
  background-image: url(../../../static/resources/images/file.png);
  background-size: 100% 100%;
  float: left;
}

.ArresterTranscribe .alarm {
  width: 12px;
  height: 13px;
  margin: 3px 2px 0 2px;
  float: left;
}
.ArresterTranscribe .normal {
  background-color: rgb(50, 150, 50);
}
.ArresterTranscribe .warning {
  background-color: rgb(0, 0, 255);
}
.ArresterTranscribe .general-alarm {
  background-color: rgb(255, 255, 0);
}
.ArresterTranscribe .serious-alarm {
  background-color: rgb(255, 128, 10);
}
.ArresterTranscribe .danger-alarm {
  background-color: rgb(155, 0, 0);
}

.urgency-task-loading {
  font-size: 39px;
}
.urgency-task-loading .el-loading-spinner .el-loading-text {
  font-size: 27px;
}
</style>